package com.pulsarwebdevelopment.concordance.plugins;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.pulsarwebdevelopment.concordance.Concordance;
import com.pulsarwebdevelopment.concordance.ConcordanceOutput;
import com.pulsarwebdevelopment.concordance.ConcordanceOutputStream;
import com.pulsarwebdevelopment.concordance.Verse;

public class BlockOccurrenceFinder implements Plugin {

	//@Override
	public void plug(PluginScreen screen) {

		screen.setTitleText("Block Word-occurrence Locator", 
				"Located words that occur in a specified number of blocks. " +
				"Blocks have an occurrence of the word at least every X (default 3) verses. " +
				"This is useful for locating potential cross-chapter questions.");
		screen.giveConcList("Choose the concordance to use.");
		screen.giveFileBrowser(FileBrowser.FileType.TEXT, "Choose file to output results to.");
		screen.giveTextField("Word set that you want your concordance to include (1 for effectivly unique words, 2 for pairs).");

	}

	//@Override
	public void go(Object[] args) {
		int concIndex = (Integer) args[0];
		File exportFile = (File) args[1];
		int requestedOccurrences = Integer.parseInt((String) args[2]);
		
		Concordance conc = new Concordance(concIndex);
		BufferedWriter outFile = null;
		
		try{
				outFile = new BufferedWriter(new FileWriter(exportFile));
				
				ConcordanceOutput<String, Verse> concOutStream = new ConcordanceOutputStream<String, Verse>(outFile, 
								ConcordanceOutputStream.ListStyle.ONE_PER_LINE);
				
				conc.getOccurrenceBlocksByNum(requestedOccurrences, concOutStream);
				
				concOutStream.flush();
				
		}catch(IOException e){
			System.out.println("Unable to open file for writing.");
		}finally{
			if(outFile != null){
				try{
					outFile.close();
				}catch(IOException e){
					System.err.println("unable to close file");
				}
			}
		}
		

	}

}
